<?php
namespace app\modules\admin\controllers;

use app\models\User;
use app\models\Util;
use Yii;
use yii\db\Query;
use yii\web\ForbiddenHttpException;

/**
 * 统计分析
 *
 * Class StatisticsController
 * @package app\modules\admin\controllers
 */
class StatisticsController extends BaseController
{
    /**
     * 用户统计
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionUser()
    {
        if (!$this->manager->can('statistics/user')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        // $search_start_date = preg_replace('/\D/', '', Yii::$app->request->get('search_start_date', date('Ymd', time() - 864000)));
        // $search_end_date = preg_replace('/\D/', '', Yii::$app->request->get('search_end_date', date('Ymd')));
        $search_split = Yii::$app->request->get('search_split');
        $table = User::find()
            ->asArray()
            ->select([
                'date'=>Util::getDateGroup(Yii::$app->db->driverName, $search_split, 'create_time'),
                'num'=>'count(0)'
            ])
            ->groupBy('date')
            ->all();
        return $this->render('user', [
            'table'=>$table
        ]);
    }

    /**
     * 资讯访问统计
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionArticle()
    {
        if (!$this->manager->can('statistics/article')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $search_split = Yii::$app->request->get('search_split');
        $table = (new Query())
            ->select([
                'date'=>Util::getDateGroup(Yii::$app->db->driverName, $search_split, 'time'),
                'num'=>'count(0)'
            ])
            ->from('{{%article_view_log}} AVL')
            ->leftJoin('{{%article}} A', 'A.id = AVL.aid')
            ->andFilterWhere(['A.cid'=>Yii::$app->request->get('search_cid')])
            ->groupBy('date')
            ->all();
        $category = (new Query())
            ->select([
                'cid'=>'A.cid',
                'cname'=>'AC.name',
                'num'=>'count(0)'
            ])
            ->from('{{%article_view_log}} AVL')
            ->leftJoin('{{%article}} A', 'A.id = AVL.aid')
            ->leftJoin('{{%article_category}} AC', 'AC.id = A.cid')
            ->andFilterWhere(['AC.pid'=>Yii::$app->request->get('search_cid')])
            ->groupBy('cid, cname')
            ->all();
        return $this->render('article', [
            'table'=>$table,
            'category'=>$category
        ]);
    }
}
